package main

import (
	"errors"
	"os/exec"
	"strings"

	"git.oschina.net/aiyao/mahonia"
)

func DoSign(input string, output string) error {
	return runCmd(conf.Signer, input, output)
}

func ZipAlign(input string, output string) error {
	return runCmd(conf.ZipAlign, input, output)
}

func runCmd(conf CmdConfig, input string, output string) error {
	args := fixArgs(conf.Args, input, output)
	cmd := exec.Command(fixPath(conf.Name), args...)

	b, err := cmd.CombinedOutput()
	if err != nil {
		es := getString(b, conf.Encoding)
		return errors.New(es)
	}

	s := getString(b, conf.Encoding)

	if strings.Contains(s, conf.SuccessFlag) {
		return nil
	}

	return errors.New(s)
}

func getString(data []byte, encoding string) string {
	charset := mahonia.GetCharset(encoding)
	if charset == nil {
		return string(data)
	}
	d := charset.NewDecoder()
	_, s, e := d.Translate(data, true)
	if e != nil {
		return string(data)
	}
	return string(s)
}

func fixArgs(orign_args []string, input string, output string) []string {
	args := make([]string, len(orign_args))
	copy(args, orign_args)

	for i, _ := range args {
		switch args[i] {
		case "{input}":
			args[i] = input
		case "{output}":
			args[i] = output
		default:
			args[i] = fixPath(args[i])
		}
	}
	return args
}

func fixPath(inputPath string) string {
	if strings.Contains(inputPath, `{~}`) {
		inputPath = strings.Replace(inputPath, `{~}`, RunPath, 100)
	}
	return inputPath
}